using System.Text;
using AdminApi.Options;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;

namespace AdminApi;

public static class HostBuiderExtend
{
    public static void Register(this WebApplicationBuilder builder)
    {
        //读取appsettings的JWTTokenOptions，注册JWT
        builder.Services.Configure<JwtTokenOptions>(builder.Configuration.GetSection("JWTTokenOptions"));

        builder.Services.AddSingleton<CustomJWTService>();
        
        #region JWT校验

        //增加鉴权逻辑
        JwtTokenOptions tokenOptions = new JwtTokenOptions();
        builder.Configuration.Bind("JWTTokenOptions", tokenOptions);
        
        //需要引入nuget包，Microsoft.AspNetCore.Authentication.JwtBearer
        builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) //Scheme
            .AddJwtBearer(options => //这里是配置的鉴权的逻辑
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    //JWT有一些默认的属性，就是给鉴权时就可以筛选了
                    ValidateIssuer = true, //是否验证Issuer
                    ValidateAudience = true, //是否验证Audience
                    ValidateLifetime = true, //是否验证失效时间
                    ValidateIssuerSigningKey = true, //是否验证SecurityKey
                    ValidAudience = tokenOptions.Audience, //
                    ValidIssuer = tokenOptions.Issuer, //Issuer，这两项和前面签发jwt的设置一致
                    IssuerSigningKey =
                        new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenOptions.SecurityKey)) //拿到SecurityKey 
                };
            });
        #endregion
    }
}